<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElTable,
  ElTableColumn,
} from "element-plus";
import ProgressBar from "@/components/ProgressBar/index.vue";
import { Plus } from "@element-plus/icons-vue";
import {
  createVerificationTask,
  startVerificationTask,
  getVerificationTaskList,
  getTaskProgress,
  getVerificationResult,
} from "../servers";

const taskList = ref<any[]>([]);
const formRef = ref<DynamicFormInstance>();
const searchFormRef = ref<DynamicFormInstance>();

const taskPagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const taskColumns = ref<TableColumn[]>([
  {
    label: "任务ID",
    prop: "task_id",
    show: true,
  },
  {
    label: "任务名称",
    prop: "task_name",
    show: true,
  },
  {
    label: "目标URL",
    prop: "target_url",
    show: true,
  },
  {
    label: "状态",
    prop: "status",
    width: 100,
    show: true,
    render: (row) => {
      return h(
        ElTag,
        { type: getStatusType(row.status), size: "small" },
        getStatusText(row.status)
      );
    },
  },
  {
    label: "进度",
    prop: "progress",
    width: 180,
    show: true,
    render: (row) => {
      const progress = row.progress || 0;
      return h(ProgressBar, {
        progress: progress,
        width: 100,
      });
    },
  },
  {
    label: "创建时间",
    prop: "created_at",
    width: 150,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 200,
    fixed: "right",
    show: true,
    slot: "taskAction",
  },
]);

const showCreateTaskDialog = ref(false);
const showResultDialog = ref(false);
const showProgressDialog = ref(false);
const taskResult = ref<any>(null);
const taskProgress = ref<any>(null);

// 搜索表单
const searchForm = reactive({
  status: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "status",
    name: "状态",
    type: "select",
    labelWidth: "80px",
    placeholder: "选择状态",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "等待中", value: "pending" },
        { label: "运行中", value: "running" },
        { label: "成功", value: "success" },
        { label: "失败", value: "failed" },
      ],
    },
  },
];

const createTaskFormData = reactive({
  target_url: "",
  task_name: "",
  target_description: "",
  sample_size: 10,
  threat_type_filter: "",
});

const createTaskFormConfig: FormItemConfig[] = [
  {
    key: "target_url",
    name: "目标URL",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入目标URL",
    rules: [{ required: true, message: "请输入目标URL" }],
  },
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入任务名称",
  },
  {
    key: "target_description",
    name: "目标描述",
    type: "textarea",
    labelWidth: "100px",
    placeholder: "请输入目标描述",
    params: {
      rows: 2,
    },
  },
  {
    key: "sample_size",
    name: "样本大小",
    type: "input",
    labelWidth: "100px",
    placeholder: "请输入样本大小",
    params: {
      type: "number",
    },
  },
  {
    key: "threat_type_filter",
    name: "威胁类型筛选",
    type: "select",
    labelWidth: "100px",
    placeholder: "选择威胁类型筛选",
    params: {
      clearable: true,
      options: [
        { label: "C&C服务器", value: "c2_server" },
        { label: "僵尸网络", value: "botnet" },
        { label: "恶意软件", value: "malware" },
        { label: "钓鱼网站", value: "phishing" },
        { label: "挖矿木马", value: "mining" },
      ],
    },
  },
];

const fetchTaskList = async () => {
  try {
    const params: any = {
      page: taskPagination.currentPage,
      page_size: taskPagination.pageSize,
      ...searchForm,
    };
    // 移除空值
    Object.keys(params).forEach((key) => {
      if (
        params[key] === "" ||
        params[key] === null ||
        params[key] === undefined
      ) {
        delete params[key];
      }
    });
    const { data } = await getVerificationTaskList(params);

    taskList.value = data?.items || [];
    taskPagination.total = data?.total || 0;
  } catch (error) {
    ElMessage.error("获取验证任务列表失败");
  }
};

const handleTaskPageChange = (page: number) => {
  taskPagination.currentPage = page;
  fetchTaskList();
};

const handleTaskSizeChange = (size: number) => {
  taskPagination.pageSize = size;
  taskPagination.currentPage = 1;
  fetchTaskList();
};

// 搜索
const handleSearch = (value?: any) => {
  if (value) Object.assign(searchForm, value);
  taskPagination.currentPage = 1;
  fetchTaskList();
};

// 重置
const handleSearchReset = () => {
  searchFormRef.value?.resetFields?.();
  Object.assign(searchForm, {
    status: "",
  });
  taskPagination.currentPage = 1;
  fetchTaskList();
};

const handleCreateTask = () => {
  Object.assign(createTaskFormData, {
    target_url: "",
    task_name: "",
    target_description: "",
    sample_size: 10,
    threat_type_filter: "",
  });
  showCreateTaskDialog.value = true;
};

const handleCloseCreateTaskDialog = () => {
  showCreateTaskDialog.value = false;
  formRef.value?.resetFields();
  Object.assign(createTaskFormData, {
    target_url: "",
    task_name: "",
    target_description: "",
    sample_size: 10,
    threat_type_filter: "",
  });
};

const handleSubmitCreateTask = async (values: any) => {
  try {
    await createVerificationTask(values);
    ElMessage.success("验证任务创建成功");
    showCreateTaskDialog.value = false;
    fetchTaskList();
  } catch (error) {
    ElMessage.error("任务创建失败");
  }
};

const handleStartTask = async (row: any) => {
  try {
    await startVerificationTask({ task_id: row.task_id });
    ElMessage.success("任务已开始");
    fetchTaskList();
  } catch (error) {
    ElMessage.error("启动任务失败");
  }
};

const handleViewTaskDetail = async (row: any) => {
  try {
    const { data } = await getTaskProgress({ task_id: row.task_id });
    taskProgress.value = data;
    showProgressDialog.value = true;
  } catch (error) {
    ElMessage.error("获取任务进度失败");
  }
};

const handleViewTaskResult = async (row: any) => {
  try {
    const { data } = await getVerificationResult({ task_id: row.task_id });
    taskResult.value = data;
    showResultDialog.value = true;
  } catch (error) {
    ElMessage.error("获取验证结果失败");
  }
};

const handleCloseResultDialog = () => {
  showResultDialog.value = false;
  taskResult.value = null;
};

const handleCloseProgressDialog = () => {
  showProgressDialog.value = false;
  taskProgress.value = null;
};

// 获取状态类型（颜色）
const getStatusType = (
  status: string
): "success" | "warning" | "info" | "danger" => {
  const statusMap: Record<string, "success" | "warning" | "info" | "danger"> = {
    success: "success",
    completed: "success", // 兼容历史
    running: "warning",
    failed: "danger",
    pending: "info",
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    success: "成功",
    completed: "已完成", // 兼容历史
    running: "运行中",
    failed: "失败",
    pending: "等待中",
  };
  return statusMap[status] || status;
};

// 获取完成率类型（颜色）
const getCompletionType = (taskProgress: any) => {
  const completed =
    (taskProgress.allowed_count || 0) + (taskProgress.blocked_count || 0);
  const total = taskProgress.total_tests || 0;
  if (total === 0) return "info";
  const rate = (completed / total) * 100;
  if (rate === 0) return "info";
  if (rate < 30) return "danger";
  if (rate < 60) return "warning";
  if (rate < 90) return "info";
  return "success";
};

// 获取成功率类型（颜色）
const getSuccessRateType = (taskProgress: any) => {
  const allowed = taskProgress.allowed_count || 0;
  const completed = allowed + (taskProgress.blocked_count || 0);
  if (completed === 0) return "info";
  const rate = (allowed / completed) * 100;
  if (rate >= 80) return "success";
  if (rate >= 60) return "info";
  if (rate >= 40) return "warning";
  return "danger";
};

// 获取剩余测试类型（颜色）
const getRemainingType = (taskProgress: any) => {
  const total = taskProgress.total_tests || 0;
  const completed =
    (taskProgress.allowed_count || 0) + (taskProgress.blocked_count || 0);
  const remaining = total - completed;
  if (remaining === 0) return "success";
  if (remaining <= total * 0.2) return "info";
  if (remaining <= total * 0.5) return "warning";
  return "danger";
};

// 暴露方法给父组件
defineExpose({
  fetchTaskList,
});

onMounted(() => {
  fetchTaskList();
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <template #header>
        <div class="card-header">
          <!-- <span>验证任务</span> -->
          <el-button type="primary" :icon="Plus" @click="handleCreateTask">
            新建验证任务
          </el-button>
          <!-- <el-button type="primary" @click="fetchTaskList"> 刷新 </el-button> -->
        </div>
      </template>

      <DynamicTable
        :columns="taskColumns"
        :data="taskList"
        :loading="false"
        :pagination="taskPagination"
        @current-page-change="handleTaskPageChange"
        @size-change="handleTaskSizeChange"
      >
        <template #taskAction="{ row }">
          <el-button
            v-if="row.status === 'pending'"
            type="warning"
            size="small"
            @click="handleStartTask(row)"
          >
            开始
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleViewTaskDetail(row)"
          >
            进度
          </el-button>
          <el-button
            v-if="row.status === 'success' || row.status === 'completed'"
            type="success"
            size="small"
            @click="handleViewTaskResult(row)"
          >
            结果
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 创建验证任务对话框 -->
    <el-dialog
      v-model="showCreateTaskDialog"
      title="创建验证任务"
      width="600px"
      @close="handleCloseCreateTaskDialog"
    >
      <DynamicForm
        ref="formRef"
        v-model="createTaskFormData"
        :form-config="createTaskFormConfig"
        :gutter="16"
        type="submit"
        @submit="handleSubmitCreateTask"
        @cancel="handleCloseCreateTaskDialog"
      />
    </el-dialog>

    <!-- 任务进度对话框 -->
    <el-dialog
      v-model="showProgressDialog"
      title="任务进度详情"
      width="600px"
      @close="handleCloseProgressDialog"
    >
      <div v-if="taskProgress">
        <el-descriptions title="进度信息" :column="2" border>
          <el-descriptions-item label="任务ID">
            {{ taskProgress.task_id }}
          </el-descriptions-item>
          <el-descriptions-item label="任务状态">
            <el-tag :type="getStatusType(taskProgress.status)">
              {{ getStatusText(taskProgress.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总体进度">
            <ProgressBar :progress="taskProgress.progress || 0" :width="200" />
          </el-descriptions-item>
          <el-descriptions-item label="当前步骤">
            {{ taskProgress.current_step || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="总测试数">
            <el-tag type="info">{{ taskProgress.total_tests || 0 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="允许数量">
            <el-tag type="success">{{
              taskProgress.allowed_count || 0
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="阻止数量">
            <el-tag type="danger">{{ taskProgress.blocked_count || 0 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="消息" :span="2">
            {{ taskProgress.message || "无" }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <h4>进度统计</h4>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="完成率">
              <el-tag :type="getCompletionType(taskProgress)">
                {{
                  taskProgress.total_tests > 0
                    ? Math.round(
                        (((taskProgress.allowed_count || 0) +
                          (taskProgress.blocked_count || 0)) /
                          taskProgress.total_tests) *
                          100
                      )
                    : 0
                }}%
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="成功率">
              <el-tag :type="getSuccessRateType(taskProgress)">
                {{
                  (taskProgress.allowed_count || 0) +
                    (taskProgress.blocked_count || 0) >
                  0
                    ? Math.round(
                        ((taskProgress.allowed_count || 0) /
                          ((taskProgress.allowed_count || 0) +
                            (taskProgress.blocked_count || 0))) *
                          100
                      )
                    : 0
                }}%
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="剩余测试">
              <el-tag :type="getRemainingType(taskProgress)">
                {{
                  (taskProgress.total_tests || 0) -
                  (taskProgress.allowed_count || 0) -
                  (taskProgress.blocked_count || 0)
                }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>

    <!-- 验证结果对话框 -->
    <el-dialog
      v-model="showResultDialog"
      title="验证结果"
      width="900px"
      @close="handleCloseResultDialog"
    >
      <div v-if="taskResult" style="height: 600px; overflow-y: auto">
        <!-- 顶部任务信息（来自 task_info） -->
        <el-descriptions title="任务信息" :column="2" border>
          <el-descriptions-item label="任务ID">
            {{ taskResult.task_info?.task_id }}
          </el-descriptions-item>
          <el-descriptions-item label="任务名称">
            {{ taskResult.task_info?.task_name || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(taskResult.task_info?.status)">
              {{ getStatusText(taskResult.task_info?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总体进度">
            <ProgressBar
              :progress="taskResult.task_info?.progress || 0"
              :width="200"
            />
          </el-descriptions-item>
          <el-descriptions-item label="目标URL">
            {{ taskResult.task_info?.target_url }}
          </el-descriptions-item>
          <el-descriptions-item label="测试模式">
            {{ taskResult.task_info?.test_mode || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="Ceye域名">
            {{ taskResult.task_info?.ceye_domain || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="Ceye标识">
            {{ taskResult.task_info?.ceye_identifier || "无" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{ taskResult.task_info?.created_by || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ taskResult.task_info?.created_at || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ taskResult.task_info?.started_at || "未知" }}
          </el-descriptions-item>
          <el-descriptions-item label="完成时间">
            {{ taskResult.task_info?.completed_at || "未知" }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 16px">
          <el-descriptions title="统计概览" :column="3" border>
            <el-descriptions-item label="样本大小">
              <el-tag type="info">{{
                taskResult.task_info?.sample_size ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总测试数">
              <el-tag type="info">{{
                taskResult.task_info?.total_tests ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="允许数量">
              <el-tag type="success">{{
                taskResult.task_info?.allowed_count ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="阻止数量">
              <el-tag type="danger">{{
                taskResult.task_info?.blocked_count ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="拦截率">
              <el-tag type="success">{{
                (taskResult.task_info?.block_rate ?? 0).toFixed
                  ? (taskResult.task_info?.block_rate ?? 0).toFixed(1) + "%"
                  : (taskResult.task_info?.block_rate ?? 0) + "%"
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="错误次数">
              <el-tag type="warning">{{
                taskResult.task_info?.error_count ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="风险等级">
              <el-tag
                :type="
                  taskResult.task_info?.risk_level === 'low'
                    ? 'success'
                    : taskResult.task_info?.risk_level === 'medium'
                    ? 'warning'
                    : 'danger'
                "
              >
                {{ taskResult.task_info?.risk_level || "unknown" }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="风险分数">
              <el-tag type="info">{{
                taskResult.task_info?.risk_score ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="当前步骤">
              {{ taskResult.task_info?.current_step || "未知" }}
            </el-descriptions-item>
            <el-descriptions-item label="错误信息" :span="3">
              {{ taskResult.task_info?.error_message || "无" }}
            </el-descriptions-item>
            <el-descriptions-item label="推荐建议" :span="3">
              <div>
                <div
                  v-for="(rec, idx) in taskResult.task_info?.recommendations ||
                  []"
                  :key="idx"
                  style="margin-bottom: 4px"
                >
                  {{ rec }}
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 测试汇总（如果后端提供 test_summary，则优先显示） -->
        <div v-if="taskResult.task_info?.test_summary" style="margin-top: 16px">
          <el-descriptions title="测试汇总" :column="3" border>
            <el-descriptions-item label="总测试数">
              <el-tag type="info">{{
                taskResult.task_info.test_summary.total_tests ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="允许数量">
              <el-tag type="success">{{
                taskResult.task_info.test_summary.allowed_count ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="阻止数量">
              <el-tag type="danger">{{
                taskResult.task_info.test_summary.blocked_count ?? 0
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="拦截率">
              <el-tag type="success">{{
                (taskResult.task_info.test_summary.block_rate ?? 0) + "%"
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="目标URL">
              {{ taskResult.task_info.test_summary.target_url || "未知" }}
            </el-descriptions-item>
            <el-descriptions-item label="建议" :span="3">
              <div>
                <div
                  v-for="(rec, idx) in taskResult.task_info.test_summary
                    .recommendations || []"
                  :key="idx"
                  style="margin-bottom: 4px"
                >
                  {{ rec }}
                </div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div style="margin-top: 20px">
          <h4>详细测试结果</h4>
          <el-table :data="taskResult.test_results || []" border>
            <el-table-column prop="test_method" label="测试方法" width="110" />
            <el-table-column prop="block_method" label="拦截方式" width="110" />
            <el-table-column prop="is_blocked" label="是否拦截" width="100">
              <template #default="{ row }">
                <el-tag :type="row.is_blocked ? 'success' : 'danger'">
                  {{ row.is_blocked ? "已拦截" : "未拦截" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="test_address" label="测试地址" width="180" />
            <el-table-column prop="test_domain" label="测试域名" width="220" />
            <el-table-column
              prop="http_status_code"
              label="HTTP状态"
              width="110"
            />
            <el-table-column
              prop="http_response_time"
              label="HTTP耗时(ms)"
              width="130"
            />
            <el-table-column
              prop="http_response_size"
              label="HTTP大小"
              width="110"
            />
            <el-table-column prop="dns_received" label="DNS返回" width="100">
              <template #default="{ row }">
                <el-tag :type="row.dns_received ? 'success' : 'info'">
                  {{ row.dns_received ? "是" : "否" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="risk_level" label="风险等级" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.risk_level === 'low'
                      ? 'success'
                      : row.risk_level === 'medium'
                      ? 'warning'
                      : 'danger'
                  "
                >
                  {{ row.risk_level || "unknown" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="threat_confirmed"
              label="威胁确认"
              width="110"
            >
              <template #default="{ row }">
                <el-tag :type="row.threat_confirmed ? 'danger' : 'info'">
                  {{ row.threat_confirmed ? "已确认" : "未确认" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="时间" width="160" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
</style>
